package vampire.com.baidumusic.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import vampire.com.baidumusic.R;
import vampire.com.baidumusic.fragment.player.PlayerBean;
import vampire.com.baidumusic.notification.PlayerNotification;
import vampire.com.baidumusic.tools.dbtools.DBHistoryPlay;
import vampire.com.baidumusic.tools.dbtools.DBMusicList;
import vampire.com.baidumusic.tools.dbtools.DBTool;
import vampire.com.baidumusic.tools.event.AskBottom;
import vampire.com.baidumusic.tools.event.AskEvent;
import vampire.com.baidumusic.tools.event.AskPlayList;
import vampire.com.baidumusic.tools.event.AskState;
import vampire.com.baidumusic.tools.event.BottomInformationEvent;
import vampire.com.baidumusic.tools.event.CleanNotifycation;
import vampire.com.baidumusic.tools.event.IsSelected;
import vampire.com.baidumusic.tools.event.NameSongIdBean;
import vampire.com.baidumusic.tools.event.PauseEvent;
import vampire.com.baidumusic.tools.event.PlayMode;
import vampire.com.baidumusic.tools.event.PlayerBeanEvent;
import vampire.com.baidumusic.tools.event.PlayerStateEvent;
import vampire.com.baidumusic.tools.event.ProgressBean;
import vampire.com.baidumusic.tools.event.ProgressEvent;
import vampire.com.baidumusic.tools.event.RequestState;
import vampire.com.baidumusic.tools.event.SaveSong;
import vampire.com.baidumusic.tools.event.SongIdEvent;
import vampire.com.baidumusic.tools.event.SongIdEventBean;
import vampire.com.baidumusic.tools.nettools.NetTool;
import vampire.com.baidumusic.values.URLVlaues;

/**
 * Created BaiDuMusic by *Vampire* on 16/8/20.
 */
public class PlayerService extends Service {
    private static final String TAG = "Vampire_PlayerSerview";

    private int position; // 当前歌曲在列表中的位置;
    private String musicID; // 歌曲id


    private PlayerBean bean; //
    private List<String> musiclList; // 传入的歌单集合
    private List typeList; // 播放模式歌单集合


    private MediaPlayer mPlayer; // 用于放歌

    private NetTool mNetTool;
    private boolean state = true;// 控制递归发送进度
    private ProgressBean progressBean;
    private int mode = 0;// 默认 顺序播放
    private List<DBMusicList> dbMusicLists;
    private SongIdEventBean songIdEventBean;
    private String pic;
    private boolean createNow = true;
    private BottomInformationEvent bottomInformationEvent;
    private String author;
    private String songName;
    private List<Integer> selectedList;
    private NameSongIdBean nameSongIdBean;
    private PlayerNotification playerNotification;
    private boolean isReady;


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getDBMusicList(SongIdEvent songIdEvent) {

        songIdEventBean = songIdEvent.getSongIdEventBean();
        musiclList = songIdEventBean.getSongIdList();
        Log.d(TAG, "songIdEventBean.getPosition():" + songIdEventBean.getPosition());
        play(songIdEventBean.getPosition());

    }

    @Subscribe
    public void requestState(AskState askState) {

            playState();
    }

    @Subscribe
    public void requestList(AskPlayList askPlayList) {
        EventBus.getDefault().post(dbMusicLists);
    }

    @Subscribe
    public void mvPlaying(PauseEvent pauseEvent){
        if (mPlayer.isPlaying()){
            playState();
        }
    }

    @Subscribe
    public void cleanNotifycation(CleanNotifycation cleanNotifycation) {
        playerNotification.getNotificationManagerCompat().cancelAll();

    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void askData(PlayerStateEvent playerStateEvent) {
        if (!createNow) {
            while (true) {
                try {
                    Thread.sleep(50);
                    ProgressEvent progressEvent = new ProgressEvent();
                    progressBean.setState(mPlayer.isPlaying());
                    progressEvent.setProgressBean(progressBean);
                    progressEvent.setNameSongIdBean(nameSongIdBean);
                    EventBus.getDefault().post(progressEvent);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    // 播放模式
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void playerMode(AskEvent askEvent) {
        while (true) {
            try {
                Thread.sleep(100);
                PlayMode playMode = new PlayMode(mode);
                EventBus.getDefault().post(playMode);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void requerBottom(AskBottom bottom) {
        EventBus.getDefault().post(bottomInformationEvent);
    }

    // 收藏存数据库
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void saveSong(SaveSong saveSong) {
        progressBean.setSelected(saveSong.isaBoolean());
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mPlayer = new MediaPlayer();
        mNetTool = new NetTool();
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return true;
            }
        });
        EventBus.getDefault().register(this);

        musiclList = new ArrayList<>();

        DBTool.getInstance().querDBMusicListByBoolean(new DBTool.QueryListener() {
            @Override
            public <T> void onQueryListener(List<T> list) {
                if (list.size() > 0) {
                    dbMusicLists = (List<DBMusicList>) list;
                    musicID = dbMusicLists.get(0).getSongId();
                    String name = dbMusicLists.get(0).getAuthor();
                    String song = dbMusicLists.get(0).getSong();
                    String pic = dbMusicLists.get(0).getPic();
                    bottomInformationEvent = new BottomInformationEvent(name, pic, song, mPlayer.isPlaying());
                }
            }
        });


        //查询上次播放列表
        DBTool.getInstance().queryDBMusicList(new DBTool.QueryListener() {
            @Override
            public <T> void onQueryListener(List<T> list) {
                dbMusicLists = (List<DBMusicList>) list;
                for (DBMusicList dbMusicList : dbMusicLists) {
                    musiclList.add(dbMusicList.getSongId());
                    Log.d("DBTool", "musiclList.size(queryDB):" + musiclList.size());
                }
            }
        });

        // 注册广播;
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.baidumusic.notification.back");
        filter.addAction("com.baidumusic.notification.next");
        filter.addAction("com.baidumusic.notification.state");
        filter.addAction("com.baidumusic.notification.clear");
        registerReceiver(receiver, filter);

    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {

        //设置前台服务 (如果id设置为0,会导致不能设置为前台service)

        if (playerNotification != null) {
            startForeground(1, playerNotification.getNotification());
        }

        // 就绪监听
        mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                RequestState requestState = new RequestState(mPlayer.isPlaying());
                EventBus.getDefault().post(requestState);
            }
        });

        //结束 监听
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

                state = false;
                playerBinder.playerNext();
            }
        });

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterReceiver(receiver);
        // 结束前台服务
        stopForeground(true);


    }

    private void upDateDBMusicList() {
        // 清空数据库
        DBTool.getInstance().cleanDBMusicList(DBMusicList.class);
        // 将播放列表存入数据库
        int position = musiclList.indexOf(musicID);
        if (songIdEventBean != null) {
            dbMusicLists = new ArrayList<>();
            for (int i = 0; i < musiclList.size(); i++) {
                if (i == position) {
                    String author = (String) songIdEventBean.getAuthor().get(i);
                    String song = (String) songIdEventBean.getSongName().get(i);
                    String songId = (String) songIdEventBean.getSongIdList().get(i);
                    DBMusicList dbMusicList = new DBMusicList(author, song, songId, pic, 100);
                    dbMusicLists.add(dbMusicList);
                    DBTool.getInstance().insertDBMusicList(dbMusicList);
                    continue;
                }

                String author = (String) songIdEventBean.getAuthor().get(i);
                String song = (String) songIdEventBean.getSongName().get(i);
                String songId = (String) songIdEventBean.getSongIdList().get(i);
                DBMusicList dbMusicList = new DBMusicList(author, song, songId, null, 0);
                dbMusicLists.add(dbMusicList);
                DBTool.getInstance().insertDBMusicList(dbMusicList);
            }
        }
    }

    private void seekToo(int progress) {
        // 获取当前播放歌曲总时长
        int duration = mPlayer.getDuration();
        int seek = (int) (progress / 100f * duration);
        mPlayer.seekTo(seek);
    }


    PlayerBinder playerBinder = new PlayerBinder();

    public class PlayerBinder extends Binder {

        // 播放
        public void playerMusic(int position) {

            play(position);
        }

        // 下一曲
        public void playerNext() {
            playNext();
        }

        // 上一曲
        public void playerBack() {
            playBack();
        }

        //快进
        public void seekTo(int progress) {
            // 快进
            PlayerService.this.seekToo(progress);
        }

        // 播放/暂停
        public void playState(boolean b) {
            PlayerService.this.playState();
        }

        //改版播放模式
        public int changeMode() {
            mode++;
            mode %= 3;

            switch (mode) {
                case 0: //顺序
                    Toast.makeText(PlayerService.this, "顺序播放", Toast.LENGTH_SHORT).show();
                    typeList = new ArrayList();
                    typeList = musiclList;
                    break;
                case 1: // 单曲循环;
                    Toast.makeText(PlayerService.this, "单曲循环", Toast.LENGTH_SHORT).show();
                    typeList = new ArrayList();
                    typeList.add(musicID);
                    break;
                case 2: // 随机播放
                    Toast.makeText(PlayerService.this, "随机播放", Toast.LENGTH_SHORT).show();
                    typeList = new ArrayList();
                    Log.d(TAG, "musiclList:" + musiclList);
                    int num = musiclList.size() - 1;
                    List<String> box = new ArrayList<>();
                    for (String s : musiclList) {
                        box.add(s);
                    }

                    for (int i = 0; i < num; i++) {
                        int id = (int) (Math.random() * (num - i));
                        String playId = box.get(id);
                        typeList.add(playId);
                        box.remove(id);
                    }
                    Log.d(TAG, "box:" + box);
                    Log.d(TAG, "typeList:" + typeList);
                    break;
            }

            return mode;
        }


        // 获取播放状态
        public int getPlayMode() {
            return mode;
        }
    }

    private void playState() {
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
            playerNotification = new PlayerNotification(PlayerService.this);
            playerNotification.showNotify(author, songName, R.mipmap.go_start);
        } else {
            if (createNow) {
                play(musiclList.indexOf(musicID));
                playerNotification = new PlayerNotification(PlayerService.this);
                playerNotification.showNotify(author, songName, R.mipmap.go_pasue);
            } else {
                mPlayer.start();
                playerNotification = new PlayerNotification(PlayerService.this);
                playerNotification.showNotify(author, songName, R.mipmap.go_pasue);
            }

        }
        RequestState requestState = new RequestState(mPlayer.isPlaying());
        EventBus.getDefault().post(requestState);
    }

    private void playBack() {
        if (typeList != null) {
            position = typeList.indexOf(musicID);
            if (position == 0) {
                play(typeList.size() - 1);
            } else {
                play(position - 1);
            }
        } else {
            if (musiclList != null) {
                position = musiclList.indexOf(musicID);
                if (position == 0) {
                    play(musiclList.size() - 1);
                } else {
                    play(position - 1);
                }

            } else {
                Toast.makeText(this, "歌单空", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void playNext() {
        if (typeList != null) {
            position = typeList.indexOf(musicID);
            if (position == typeList.size() - 1) {
                play(0);
            } else {
                play(position + 1);
            }
        } else {
            if (musiclList != null) {
                position = musiclList.indexOf(musicID);
                if (position == musiclList.size() - 1) {
                    play(0);
                } else {
                    play(position + 1);
                }

            } else {
                Toast.makeText(this, "歌单空", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void play(int position) {
        createNow = false;
        isReady = false;
        if (position != -1 && musiclList.size() > 0) {
            this.musicID = musiclList.get(position);
            mNetTool.getNetData(URLVlaues.PLAY_FRONT + musicID + URLVlaues.PLAY_BEHIND,
                    PlayerBean.class, new NetTool.NetListener<PlayerBean>() {
                        @Override
                        public void onSuccess(PlayerBean playerBean) {
                            bean = playerBean;
                            try {

                                PlayerBeanEvent playerBeanEvent = new PlayerBeanEvent();
                                playerBeanEvent.setPlayerBean(playerBean);
                                // 图片 用于左下角
                                if (playerBean.getSonginfo().getPic_premium() != null) {
                                    pic = playerBean.getSonginfo().getPic_premium();
                                }
                                author = playerBean.getSonginfo().getAuthor();
                                songName = playerBean.getSonginfo().getTitle();
                                nameSongIdBean = new NameSongIdBean(author, musicID, songName);
                                EventBus.getDefault().post(playerBeanEvent);

                                mPlayer.reset();
                                mPlayer.setDataSource(playerBean.getBitrate().getFile_link());
                                mPlayer.prepareAsync();
                                mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                    @Override
                                    public void onPrepared(MediaPlayer mp) {
                                        mp.start();
                                        state = true;

                                    }

                                });
                                // 历史播放
                                DBHistoryPlay historyPlay = new DBHistoryPlay(author, musicID, songName);
                                DBTool.getInstance().insertDBHistory(historyPlay, musicID);

                                playerNotification = new PlayerNotification(PlayerService.this);
                                playerNotification.showNotify(author, songName, R.mipmap.go_pasue);

                                isFavorite();
                                upDateDBMusicList();
                                progress();


                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onError(String errorMsg) {
                            Log.d(TAG, "没网");
                        }
                    });

        } else {
            Toast.makeText(this, "没歌", Toast.LENGTH_SHORT).show();
        }



    }

    private void isFavorite() {
        DBTool.getInstance().queryDBMyMusicList(musicID, new DBTool.QueryListener() {
            @Override
            public <T> void onQueryListener(List<T> list) {
                Log.d("Vampire_PICFragment" +
                        "", "list.size():" + list.size());
                if (list.size() == 0) {
                    IsSelected isSelected = new IsSelected(false);
                    EventBus.getDefault().post(isSelected);
                } else {
                    IsSelected isSelected = new IsSelected(true);
                    EventBus.getDefault().post(isSelected);
                }
            }
        });
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return playerBinder;
    }

    private void progress() {
        // 歌曲进度获取线程
        Log.d("Vampire_LyircFragment", "progress");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (state = true) {
                    sleep();
                    if (selectedList != null) {
                        Log.d(TAG, "selectedList.size():" + selectedList.size());
                        if (selectedList.indexOf(musiclList.indexOf(musicID)) > -1) {
                        }
                    }
                    if (mPlayer.isPlaying()) {
                        int seek = mPlayer.getCurrentPosition();
                        int percent = (seek * 100 / mPlayer.getDuration());
                        progressBean = new ProgressBean(
                                bean.getSonginfo().getAuthor()
                                , percent
                                , bean.getSonginfo().getTitle()
                                , mPlayer.getCurrentPosition()
                                , mPlayer.getDuration()
                                , bean.getSonginfo().getPic_radio()
                                , bean.getSonginfo().getLrclink(),
                                mPlayer.isPlaying(),
                                mode, musicID);

                    } else {
                        continue;
                    }
                }
            }


            private void sleep() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "com.baidumusic.notification.back":
                    playBack();
                    break;
                case "com.baidumusic.notification.next":
                    playNext();
                    break;
                case "com.baidumusic.notification.state":
                    playState();
                    break;
                case "com.baidumusic.notification.clear":
                    playerNotification.getNotificationManagerCompat().cancelAll();
                    mPlayer.pause();
                    break;
            }
        }
    };
}
